package bmatch.tech.cloud.resource;

import bmatch.tech.cloud.auth.Jwtutil;
import bmatch.tech.cloud.model.User;
import bmatch.tech.cloud.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
import java.net.URI;
import java.util.Date;

/**
 * 用户资源
 *
 * @author: Awake
 * @date: 2018-12-12 14:40
 **/
@Component
@Path("user")
public class UserResource {

    /**
     * 日志输出
     */
    private static Logger log = LoggerFactory.getLogger(UserResource.class);

    /**
     * 用户服务类
     */
    UserService userService;

    @Autowired
    public UserResource(UserService userService) {
        this.userService = userService;
    }

    /**
     * 登陆验证
     *
     * @param user
     * @return
     */
    @POST
    @Path("login")
    @Produces("text/html")
    public Response login(User user) {
        String userId = userService.login(user.getName(), user.getPwd());
        //登录失败
        if (userId == null) {
            return Response.status(401).build();
        }
        //登录成功并跳转到/demo,将token的cookie传回以便于之后验证
        else {
            String token = Jwtutil.generator(userId);
            //创建一个NewCookie,并指定path为/
            NewCookie cookie = new NewCookie("sid",
                    "Bearer " + token,
                    "/",
                    (String) null, 1, (String) null, -1, (Date) null, false, false);
            //转发
            URI uri = URI.create("/display?path=/");
            return Response.seeOther(uri)
                    .cookie(cookie).build();
        }

    }
}
